package com.alex.ip.holder.server.service.impl;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import cn.hutool.core.collection.CollUtil;
import com.alex.ip.holder.common.enums.AlexResult;
import com.alex.ip.holder.common.vo.ClientVO;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于内存的服务管理:默認實現
 * <p>
 * 如有特殊需求支持重寫
 *
 * @author Alex.Liu
 * @date: 2025-02-18 15:49
 * @since 1.0.0
 */
@Slf4j
public class DefaultInMemoryClientService extends AbstractClientService {

    private static final FIFOCache<String, List<ClientVO>> cache = CacheUtil.newFIFOCache(5000);

    @Override
    public String register(ClientVO clientVO) {
        // 緩存源信息
        if (CollUtil.isEmpty(cache.get(clientVO.getServerId()))) {
            cache.put(clientVO.getServerId(), CollUtil.newArrayList(clientVO));
        } else {
            cache.get(clientVO.getServerId()).add(clientVO);
        }
        return AlexResult.SUCCESS.name();
    }

    @Override
    protected List<ClientVO> getClientList() {
        List<ClientVO> copy = new ArrayList<>();
        cache.forEach(copy::addAll);
        return copy;
    }

    @Override
    protected Boolean update(List<ClientVO> clients) {
        if (CollUtil.isEmpty(clients)) {
            log.info("更新客戶端失敗:無需要更新的客戶端");
            return Boolean.FALSE;
        }
        Map<String, List<ClientVO>> updated = clients.stream().collect(Collectors.groupingBy(ClientVO::getServerId));
        cache.clear();
        updated.forEach(cache::put);
        return Boolean.TRUE;
    }
}
